package com.example.bookapp.fragments;



import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class CartFragment extends Fragment {
    private static final String TAG = "CartFragment";
    RecyclerView rvCart;
    ClothAdapter adapter;
    List<ClothBean> cart;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_cart, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        rvCart = view.findViewById(R.id.rvCart);

        cart = SPUtil.getListData(Const.CART, ClothBean.class);
        adapter = new ClothAdapter();
        rvCart.setAdapter(adapter);
        adapter.setNewData(cart);

        view.findViewById(R.id.btCart).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cart.size() > 0) {
                    List order = SPUtil.getListData(Const.ORDER, ClothBean.class);
                    order.addAll(cart);
                    SPUtil.putListData(Const.ORDER, order);

                    SPUtil.putData(Const.CART, "[]");
                    flushCart();

                    Toast.makeText(getContext(), "购买成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getContext(), "购物车中没有商品", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void flushCart() {
        cart = SPUtil.getListData(Const.CART, ClothBean.class);
        Log.d(TAG, "flushCart: " + cart.size() + cart);
        adapter.setNewData(cart);
    }
}